import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {Http, Headers, Response} from '@angular/http';
import {User} from '../model/user-model';

@Injectable()
export class UserLoginService {
  public userLoginURL = 'http://localhost:3000/signin';
  public subject: Subject<User> = new Subject<User>();

  constructor(public http: Http) {
  }

  public get currentUser(): Observable<User> {
    return this.subject.asObservable();
  }

  public login(user: User) {
    return this.http
      .post(this.userLoginURL, user)
      .map((response: Response) => {
        let user = response.json();

        if (!user.error) {
          localStorage.setItem("currentUser", JSON.stringify(user));
          this.subject.next(Object.assign({}, user));
        }
        return user;
      });
  }

  /*public login(user: User) {
      this.userLoginURL = 'mock-data/user-login-mock.json';
      return this.http
        .get(this.userLoginURL)
        .map((response: Response) => {
          let user = response.json();
          console.log("user object>" + user);
          if (user && user.token) {
            localStorage.setItem("currentUser", JSON.stringify(user));
            //this.subject.next(Object.assign({}, user));
            this.subject.next(Object.assign({}));
          }
          return response;
        });

    }*/

  public logout(): void {
    localStorage.removeItem("currentUser");
    this.subject.next(Object.assign({}));
    this.http.get('http://localhost:3000/signout')
  }
}
